#include "iodialog.h"
#include "ui_iodialog.h"

#include "dataiointerface.h"
#include "tableinfomodle.h"

#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <QDebug>

struct IODialogPrivate {
    DataIOInterface* ioModule = nullptr;
    QString format = "";
    bool isExport = false;
    TableInfoModel* infoModel = nullptr;
    IoEditFrameInterface* frame = nullptr;
    bool isEdit = false;
};

IODialog::IODialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::IODialog)
{
    ui->setupUi(this);
    m_d = new IODialogPrivate();
    ui->stackedWidget->setCurrentIndex(0);
    setupConnect();


    ui->tableView_info->setAlternatingRowColors(true);  // 启用交替行颜色
    // 设置行高
    ui->tableView_info->verticalHeader()->setDefaultSectionSize(32);  // 默认行高
    ui->tableView_info->verticalHeader()->setMinimumSectionSize(24);  // 最小行高

    // 设置列宽自适应
    ui->tableView_info->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableView_info->horizontalHeader()->setStretchLastSection(true);  // 最后一列填充剩余空间

    // 设置表格整体样式
    ui->tableView_info->setStyleSheet(
        // 表格基础样式
        "QTableView {"
        "   background-color: #FFFFFF;"          // 表格背景色
        "   gridline-color: #E0E0E0;"            // 网格线颜色
        "   font-family: 'Segoe UI';"            // 字体
        "   font-size: 12px;"                    // 字号
        "}"

        // 表头样式
        "QHeaderView::section {"
        "   background-color: #F5F5F5;"          // 表头背景
        "   color: #333333;"                     // 表头文字颜色
        "   padding: 8px;"                       // 表头内边距
        "   border: 1px solid #E0E0E0;"          // 边框颜色
        "}"

        // 行交替颜色（可选）
        "QTableView::item:alternate {"
        "   background-color: #F8F9FA;"          // 交替行背景色
        "}"

        // 选中行高亮样式
        "QTableView::item:selected {"
        "   background-color: #E3F2FD;"          // 选中行背景色
        "   color: #1976D2;"                     // 选中行文字颜色
        "}"

        // 滚动条样式
        "QScrollBar:vertical {"
        "   background: #FFFFFF;"                // 滚动条背景
        "   width: 12px;"                        // 滚动条宽度
        "}"
        "QScrollBar::handle:vertical {"
        "   background: #BDBDBD;"                // 滚动条滑块颜色
        "   border-radius: 6px;"                 // 圆角
        "}"
        );

}

IODialog::~IODialog()
{
    delete m_d;
    delete ui;
}

void IODialog::bingingIoModule(DataIOInterface* ioModule,
                               bool isExport,
                               const QString& format)
{
    m_d->ioModule = ioModule;
    m_d->isExport = isExport;
    m_d->format = format;
    updateInfoModel();
    //设置第二页数据
    if (isExport) {
        m_d->frame = ioModule->exportUI(format);
        ui->vlayout_create->addWidget(m_d->frame);
    }
    updateWindowsTitle();
}

void IODialog::setupConnect()
{
    //菜单
    ui->tableView_info->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->tableView_info, &QWidget::customContextMenuRequested, this, &IODialog::showContextMenu);

    //
    connect(ui->pbtn_create_ok, &QPushButton::clicked, [this](){
        if (m_d->frame) {
            if(!m_d->isEdit && !m_d->frame->save())
                return;
            if (m_d->isEdit && !m_d->frame->update())
                return;
        }
        updateInfoModel();
        ui->stackedWidget->setCurrentIndex(0);
         updateWindowsTitle();
    });

    connect(ui->pbtn_create_cancle, &QPushButton::clicked, [this](){
        ui->stackedWidget->setCurrentIndex(0);
        updateWindowsTitle();
    });
    connect(ui->pbtn_create, &QPushButton::clicked, this, &IODialog::createInfo);
    connect(ui->pbtn_edit, &QPushButton::clicked, this, &IODialog::editInfo);
    connect(ui->pbtn_delete, &QPushButton::clicked, this, &IODialog::removeInfo);

    connect(ui->pbtn_createbaseon, &QPushButton::clicked, this, &IODialog::createBaseOn);

    connect(ui->pbtn_close, &QPushButton::clicked, this, &IODialog::reject);
}


void IODialog::updateInfoModel()
{
    // 保存当前选中的名称
    const auto& infoHeader = m_d->ioModule->exportInfoHeaders(m_d->format);
    if (m_d->infoModel == nullptr) {
        m_d->infoModel = new TableInfoModel(infoHeader, this);
        ui->tableView_info->setModel(m_d->infoModel);
        ui->tableView_info->setSelectionBehavior(QAbstractItemView::SelectRows);
    }

    const auto& infoModels = m_d->ioModule->exportInfoModels(m_d->format);
    m_d->infoModel->updateInfo(infoModels);
}

void IODialog::showContextMenu(const QPoint &pos)
{
    QMenu menu(this);

    // 添加菜单项
    QAction* action1 = menu.addAction("Create New");

    // 获取当前选中的行和列
    // QModelIndex index = ui->tableView_info->indexAt(pos);

    // 连接信号和槽
    connect(action1, &QAction::triggered, this, &IODialog::createInfo);

    // 显示菜单
    menu.exec(mapToGlobal(pos));
}

void IODialog::createInfo()
{
    m_d->isEdit = false;
    m_d->frame->reInitUI();
    ui->stackedWidget->setCurrentIndex(1);
    updateWindowsTitle();
}

void IODialog::createBaseOn()
{
    m_d->isEdit = false;

    auto names = selectTableNames();
    if (names.isEmpty()) {
        QMessageBox::information(this, "提示", tr("请选取一个数据进行编辑"));
        return;
    }

    m_d->frame->createBaseOn(names[0]);
    ui->stackedWidget->setCurrentIndex(1);
    updateWindowsTitle();
}

void IODialog::editInfo()
{
    if (!m_d->frame) return;
    m_d->isEdit = true;
    auto names = selectTableNames();
    if (names.isEmpty()) {
        QMessageBox::information(this, "提示", tr("请选取一个数据进行编辑"));
        return;
    }
    m_d->frame->editUI(names[0]);
    ui->stackedWidget->setCurrentIndex(1);
     updateWindowsTitle();
}

void IODialog::removeInfo()
{
    auto names = selectTableNames();
    if (names.isEmpty()) {
        QMessageBox::information(this, "提示", tr("请选取一个数据进行删除"));
        return;
    }
    m_d->ioModule->removeTable(m_d->format, names);
    updateInfoModel();
}

QStringList IODialog::selectTableNames()
{
    // 获取选择模型
    QItemSelectionModel* selectionModel = ui->tableView_info->selectionModel();

    // 获取选中的行索引
    QModelIndexList selectedRows = selectionModel->selectedRows();
    auto infos = m_d->infoModel->infoData();
    QSet<int> rows;
    for (const QModelIndex& index : selectedRows) {
        rows.insert(index.row());
    }

    // 遍历选中的行
    QStringList names;
    for (const auto row : rows) {
        auto info = infos[row];
        names << info["Name"].toString();
    }

    return names;
}

void IODialog::updateWindowsTitle()
{
    QString title = "";
    auto index = ui->stackedWidget->currentIndex();
    if (index == 0) {
        title = m_d->isExport ? tr("Export - list %1").arg(m_d->format) : tr("Import - list %1").arg(m_d->format);
    } else {
        auto tmpTitle = !m_d->isEdit ? tr("create %1").arg(m_d->frame->title()) :
                            tr("edit %1").arg(m_d->frame->title());
         title = m_d->isExport ? tr("Export - %1").arg(tmpTitle) : tr("Import - %1").arg(tmpTitle);
    }
    this->setWindowTitle(title);
}


